package com.guanghua.brick.db.extend.hibernate;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.hibernate.MappingException;
import org.hibernate.cfg.Configuration;

import com.guanghua.brick.util.FileUtil;

/**
 * @author Administrator
 *
 * 更改所生成类型注释的模板为
 * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
 */
public class ExtendHBConfiguration extends Configuration {
	
	private static Log logger = LogFactory.getLog(ExtendHBConfiguration.class);
	
	@Override
	protected void parseMappingElement(Element arg0, String arg1) {
		try {
			//正常情况调用父类的方法
			super.parseMappingElement(arg0, arg1);
		} catch (MappingException ex) {
			//出现异常,那么判断是否是因为pkg填写造成的,
			//如果是load pkg下的所有hbm.xml,否则抛出
			Attribute pkg = arg0.attribute( "pkg" );
			logger.debug("search hbm file in hibernate package: [" + pkg + "]");			
			if (pkg != null) {
				try {
					List list = FileUtil.searchFileFromClassPath(pkg.getValue(), "[\\w]*.hbm.xml");
					Iterator iterator = list.iterator();
					while (iterator.hasNext()) {
						String file = iterator.next().toString();						
						try {
							super.addResource(file);
						} catch (Exception e) {
							logger.error("hibernate config: [" + file + "] not load success" );
						}
					}
				} catch (Exception e) {
					logger.error("search pkg to load hibernate config wrong", e);
				}
			} else
				throw ex;			
		}
		
	}

}
